package com.tms.firtsp.WebApi;

import com.tms.firtsp.common.Result;
import com.tms.firtsp.common.ResultUtil;
import com.tms.firtsp.entities.Student;
import com.tms.firtsp.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/webapi/student")
public class StudentRestController  extends  BaseRestController{

    @Autowired
    StudentService studentService;

    @RequestMapping("/add")
    public Result<Student> add(@Valid Student student, BindingResult bindingResult) throws  Exception{
       // throw new Exception("哈哈哈，出错了！");
        if(bindingResult.hasErrors()){

            log.info("验证出错:{}",bindingResult.getFieldError().getDefaultMessage());
            return null;
        }
        student=studentService.save(student);
        return ResultUtil.success(student);
    }


    @RequestMapping("delete/{id}")
    public  boolean delete(@PathVariable Integer id){

        studentService.delete(id);

        return  true;
    }

  @RequestMapping("/update")
    public  Result<Student>  update(Student student){
        student=studentService.update(student);



      return ResultUtil.success(student);
    }

    @RequestMapping("/get/{id}")
    public Student getById(@PathVariable  Integer id){

        return studentService.findOne(id);

    }

    @RequestMapping("/getAll")
    public List<Student> getAll(){

        return studentService.findAll();

    }
    @RequestMapping("/delete")
    public void delete(@RequestParam("ids[]") Integer[] ids){

//        String[] newids=ids.split(",");
//        System.out.println(newids.length);
         studentService.delete(ids);

    }

    @RequestMapping("/validUserNameAndPassword")
    public Result validUserNameAndPassword(String userName,String password)throws Exception{

        if(studentService.validUserNameAndPassword(userName,password)){
            return ResultUtil.success();

        }else{
            return ResultUtil.error(-1,"出错了！");
        }


    }
}
